Rails Callback
Callback
Do something before, after model operations
- before_validation
- after_validation
- before_save
- around_save
- before_create
- before_update
- before_destroy
- after_create
- after_update
- after_save
- after_find
- after_initialize
create/update/destroy
create, create!, decrement, destroy
destroy!, destroy_all, increment!, save
save!, toggle!, update, update_attribute, valid?
after_find
all, first, find, find_by, find_by_sql, last
after_initialize
new
Example
class Review < ActiveRecord::Base
after_destroy :log_history
private
def log_history
logger.info('deleted:' + self.inspect)
end
end
[/ruby]
basically, call back should be defined as private
<h3>Condition<h3>
[ruby]
after_destroy :log_histroy, unless: Proc.new { |r| r.name == "great" }
block callback
class Review < ActiveRecord::Base
after_destroy do |r|
logger.info('deleted: ' + r.inspect)
end
end
[/ruby]
<h3>Create callback class</h3>
Example
[ruby]
class ReviewCallbacks
cattr_accessor :logger
self.logger ||= Rails.logger
def after_destroy(r)
logger.info('deleted: ' + r.inspect)
end
end
class Review < ActiveRecord::Base after_destroy ReviewCallbacks.new end [/ruby]
